package com.bjshiwei.zhengu.httputils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 作者：Administrator on 2017/2/9 0009 19:22
 * 邮箱：sanjins@126.com
 */


public class NetWorks {
    private static NetWorks instance;
    private static final String baseUrl="";
    private static final int TIME_OUT = 20;
    private Api api;

    private NetWorks(){}

    public static synchronized NetWorks getNetWorks(){
        if(instance==null) {
            instance = new NetWorks();
        }
        return instance;
    }

    /**
     * 初始化retrofit，配置
     */
    public <T> T createRetrofit(Class<T> service){
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(getOkHttpClient())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create(createGson()))
                .build();
        return retrofit.create(service);
    }

    public OkHttpClient getOkHttpClient(){
       return   new OkHttpClient.Builder()
                .connectTimeout(TIME_OUT, TimeUnit.SECONDS)
                .build();
    }

    public Gson createGson(){
        return new GsonBuilder()
                .setDateFormat("yyyy-MM-dd HH:mm:ss")
                .registerTypeAdapter(Integer.class, new IntegerDefaultAdapter())
                .registerTypeAdapter(int.class, new IntegerDefaultAdapter())
                .create();
    }


    public Api getApi(){
        return api==null? createRetrofit(Api.class) :api;
    }
}
